import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

@Component({
    selector: 'app-forget',
    templateUrl: './forget.component.html',
    styleUrls: ['./forget.component.css']
})
export class ForgetComponent implements OnInit {
    current = 0;
    code = '';
    email: String = '';
    password: String = '';
    passwordRep: String = '';
    haveEmail: Boolean = true;
    codeIsRight: Boolean = true;
    isRep: Boolean = true;
    private validateUrl = '/api/User/ConfirmHaveEmail';
    private sendEmail = '/api/User/SendEmail';
    private validateCodeUrl = '/api/User/ValidateCode';
    private AlterPasswordUrl = '/api/User/AlterPassword';

    pre() {
        this.current -= 1;
    }
    next() {
        this.current += 1;
    }

    validate() {
        if (this.current == 0) {
            this.validateEmail();
        } else if (this.current == 1) {
            this.validateCode();
        }
    }

    // 修改密码
    validatePassword() {
        this.isRep = this.passwordRep == this.password;
        if (this.isRep) {
            this.http
                .get(
                    `${this.AlterPasswordUrl}?email=${this.email}&password=${
                        this.password
                    }`
                )
                .subscribe(response => {
                    this.next();
                    setTimeout(_ => {
                        this.router.navigate(['/login']);
                    }, 3000);
                });
        }
    }

    // 验证code
    validateCode() {
        this.http
            .get(
                `${this.validateCodeUrl}?email=${this.email}&randNum=${
                    this.code
                }`
            )
            .subscribe(response => {
                if (response as boolean) {
                    this.next();
                } else {
                    this.codeIsRight = false;
                }
            });
    }

    // 验证邮箱是否存在
    validateEmail() {
        this.http
            .get(`${this.validateUrl}?email=${this.email}`)
            .subscribe(response => {
                console.log(response);
                this.haveEmail = response as boolean;
                if (this.haveEmail) {
                    this.http
                        .get(`${this.sendEmail}?email=${this.email}`)
                        .subscribe(res => {
                            this.haveEmail = res as boolean;
                            if (this.haveEmail) {
                                this.next();
                            }
                        });
                }
            });
    }

    constructor(
        private _message: NzMessageService,
        private http: HttpClient,
        private router: Router
    ) {}

    ngOnInit() {}
}
